package com.topvision.common.token;

import com.topvision.common.exception.BusinessException;
import com.topvision.config.TopvisionProperties;
import com.topvision.utils.base.SpringContextHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;

import java.util.List;
import java.util.Optional;

/**
 * @author shengwm
 * @version V0.0.1
 * @Title: RefreshToken
 * @Package com.seed.common.security.token
 * @Description: 刷新JWT令牌模型
 * @date 2017/6/17 17:09
 */
public class RefreshToken {
    private static TopvisionProperties topvisionProperties = SpringContextHolder.getBean(TopvisionProperties.class);

    private Jws<Claims> claims;

    public RefreshToken(Jws<Claims> claims) {
        this.claims = claims;
    }

    public Jws<Claims> getClaims() {
        return claims;
    }

    public String getJti() {
        return claims.getBody().getId();
    }

    public String getSubject() {
        return claims.getBody().getSubject();
    }

    /**
     * 创建并验证刷新令牌
     *
     * @param token
     * @param signingKey
     * @return
     */
    public static Optional<RefreshToken> createRefreshToken(RawAccessToken token) {
        Jws<Claims> claims = token.parseClaims(topvisionProperties.getSecurity().getAuthentication().getJwt().getTokenSigningKey());

        List<String> scopes = claims.getBody().get("scopes", List.class);
        if (scopes == null || scopes.isEmpty()
                || !scopes.stream().filter(scope -> "refresh_token".equals(scope)).findFirst().isPresent()) {
            throw new BusinessException("invalid_refresh_token", "JWT刷新令牌无效");
        }

        return Optional.of(new RefreshToken(claims));
    }
}
